package com.gdssoft.pdaweb.action.water;
/*
 *  捷达世软件（深圳）有限公司
 *  Copyright (C) 2008-2010 ShenZhen JieDaShi Software Limited Company.
*/
import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import com.gdssoft.core.command.QueryFilter;
import com.gdssoft.core.util.BeanUtil;
import com.gdssoft.core.util.ContextUtil;
import com.gdssoft.core.util.DateUtil;
import com.gdssoft.core.web.action.BaseAction;
import com.gdssoft.framework.model.system.AppUser;
import com.gdssoft.framework.service.system.DepartmentService;
import com.gdssoft.pdaweb.model.am.PdaAmMeterList;
import com.gdssoft.pdaweb.model.water.PdaWaterList;
import com.gdssoft.pdaweb.model.water.PdaWaterMeter;
import com.gdssoft.pdaweb.model.water.WaterMeterPlan;
import com.gdssoft.pdaweb.service.water.PdaWaterListService;
import com.gdssoft.pdaweb.service.water.PdaWaterMeterService;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import flexjson.JSONSerializer;
/**
 * 
 * @author 
 *
 */
public class PdaWaterListAction extends BaseAction{
	@Resource
	private PdaWaterListService pdaWaterListService;
	@Resource
	private DepartmentService departmentService;
	@Resource
	private PdaWaterMeterService pdaWaterMeterService;

	private Long id;
	private File file;
	private String fileFileName;
	private String fileName;
	private String filePath;
	private String importMonth;
	private PdaWaterList pdaWaterList;
	
	public PdaWaterListService getPdaWaterListService() {
		return pdaWaterListService;
	}

	public void setPdaWaterListService(PdaWaterListService pdaWaterListService) {
		this.pdaWaterListService = pdaWaterListService;
	}

	public PdaWaterList getPdaWaterList() {
		return pdaWaterList;
	}

	public void setPdaWaterList(PdaWaterList pdaWaterList) {
		this.pdaWaterList = pdaWaterList;
	}

	public Long getId() {
		return id;
	}

	public void setId(Long id) {
		this.id = id;
	}

	public PdaWaterMeterService getPdaWaterService() {
		return pdaWaterMeterService;
	}

	public void setPdaWaterService(PdaWaterMeterService pdaWaterService) {
		this.pdaWaterMeterService = pdaWaterService;
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}

	public String getFileFileName() {
		return fileFileName;
	}

	public void setFileFileName(String fileFileName) {
		this.fileFileName = fileFileName;
	}

	public String getFileName() {
		return fileName;
	}

	public void setFileName(String fileName) {
		this.fileName = fileName;
	}

	public String getFilePath() {
		return filePath;
	}

	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}

	public String getImportMonth() {
		return importMonth;
	}

	public void setImportMonth(String importMonth) {
		this.importMonth = importMonth;
	}

	/**
	 * 导入文件
	 * @return
	 */
	public String saveExcel() {
		List<PdaWaterList> errorList = pdaWaterListService.checkXLSFormat(importMonth,file);
		StringBuffer buff = new StringBuffer("{\"success\":true,\"totalCounts\":");
		
		if(errorList.size()== 0){
			int count = pdaWaterListService.saveExcel(importMonth,file);
			buff.append(count);
			buff.append(",\"flag\": 0");
		}else{
			buff.append(errorList.size());
			JSONSerializer serializer=new JSONSerializer();
			buff.append(",\"flag\": 1");
			buff.append(",\"result\":");
	        buff.append(serializer.exclude(new String[] { "class" }).serialize(errorList));
			
		}
		buff.append("}");
		jsonString=buff.toString();
		return SUCCESS;
	}
	
	//导出
	public void exportExcel() {
		if(!pdaWaterList.getMonth().isEmpty()){
			AppUser appUser = ContextUtil.getCurrentUser();
			PdaAmMeterList pl = new PdaAmMeterList();
			pl.setMonth(pdaWaterList.getMonth());
			String deptId = departmentService.getSubDepIds();
			pdaWaterListService.excelExport(getResponse(),pdaWaterList,appUser.getUsername(),deptId);
		}	
	}
	
	
	/**
	 * 显示列表
	 */
	public String query(){
		List<PdaWaterList> meterList = new ArrayList<PdaWaterList>();
		int count = 0;
		if(pdaWaterList != null){
			count = pdaWaterListService.queryCount(pdaWaterList);
			if(getStart()< count){
				int to = getStart()+getLimit();		
				meterList = pdaWaterListService.query(pdaWaterList,getStart(),to>count?count:to);
			}	
		}
		JSONSerializer serializer=new JSONSerializer();
		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
		.append(count).append(",result:");		
        buff.append(serializer.exclude(new String[] { "class" }).serialize(meterList));
		buff.append("}");
				
		jsonString=buff.toString();		
		return SUCCESS;		
	}
	
	/**
	 * 显示列表
	 */
	public String list(){
		String depIds = departmentService.getSubDepIds();
		
		Map paramsMap = getRequest().getParameterMap();
		Map params = new HashMap();
		for(Object str : paramsMap.keySet()){
			String []as = (String[])paramsMap.get((String)str);
			if(as.length>0)params.put((String)str,as[0]);
		}
		
		String ss = (String)params.get("Q_status_S_SIN");
		if(ss != null && !ss.isEmpty())for(String s:ss.split(",")) Integer.parseInt(s);//check isNum
				
		List<PdaWaterList> list = pdaWaterListService.getList(params,depIds);
		int count = pdaWaterListService.getListCount(params,depIds);
		
		JSONSerializer serializer=new JSONSerializer();
		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
		.append(count).append(",result:");		
        buff.append(serializer.exclude(new String[] { "class" }).serialize(list));
		buff.append("}");
		
		jsonString=buff.toString();	
		
		return SUCCESS;		
	}
	
	/**
	 * 显示列表
	 */
	public String searchList(){
		QueryFilter filter=new QueryFilter(getRequest());
		List<PdaWaterList> list= pdaWaterListService.getSearchList(filter);
		List<PdaWaterList> list1= new ArrayList<PdaWaterList>();
		for(int i=0;i<list.size();i++){
			list.get(i).setLastDegree(pdaWaterListService.getPdaWaterList(list.get(i)));
		}
		
		JSONSerializer serializer=new JSONSerializer();
		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
		.append(filter.getPagingBean().getTotalItems()).append(",result:");		
        buff.append(serializer.exclude(new String[] { "class" }).serialize(list));
		buff.append("}");
				
		jsonString=buff.toString();		
		return SUCCESS;		
	}
	/**
	 * 显示详细信息
	 * @return
	 */
	public String get(){
		PdaWaterList pdaWaterList=pdaWaterListService.get(id);
		
		Gson gson=new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
		//将数据转成JSON格式
		StringBuffer sb = new StringBuffer("{success:true,data:");
		sb.append(gson.toJson(pdaWaterList));
		sb.append("}");
		setJsonString(sb.toString());
		
		return SUCCESS;
	}
	/**
	 * 添加及保存操作
	 */
	public String save(){
		AppUser au = ContextUtil.getCurrentUser();
		String updateDate = DateUtil.dateFormat(new Date(), "yyyy-MM-dd");
		pdaWaterList.setLasteditby(au.getUsername());
		pdaWaterList.setLasteditdt(updateDate);
		pdaWaterList.setUpdataId(au.getUsername());
		pdaWaterList.setUpdateDate(updateDate);
		if(pdaWaterList.getId()==null){
			try {
				pdaWaterListService.save(pdaWaterList);
			} catch (Exception e) {
				logger.error("SAVE pdaAmMeterList ERROR:"+e.getMessage());
			}
		}else{
			PdaWaterList orgPdaWaterList=pdaWaterListService.get(pdaWaterList.getId());
			String status = pdaWaterListService.checkNomal(orgPdaWaterList.getAmId(), pdaWaterList.getDegree(), orgPdaWaterList.getMonth());
			pdaWaterList.setStatus(status);
			pdaWaterList.setTranscribeType(1);
			pdaWaterList.setRecorderId(au.getUsername());//add_by_guo_201304181700
			try{
				BeanUtil.copyNotNullProperties(orgPdaWaterList, pdaWaterList);
				pdaWaterListService.save(orgPdaWaterList);
			}catch(Exception ex){
				logger.error(ex.getMessage());
			}			
		}
		setJsonString("{success:true}");
		return SUCCESS;
	}
	/**
	 * 审核
	 * @return
	 */
	public String check(){
		String ids = fileName.trim();
		if(ids.endsWith(",")){
			ids = ids.substring(0, ids.length()-1);
		}
		if(ids.contains("'")){
			setJsonString("{success:false}");
		}else{
			String status = "1"; //通过
			setJsonString("{success:"+pdaWaterListService.check(ids,status)+"}");
		}
		return SUCCESS;
	}
	
	/**
	 * 修正
	 */
	public String saveFixedUsage(){
		jsonString = "{success:" + pdaWaterListService.saveFixedUsage(pdaWaterList)+"}"; 
		return SUCCESS;
	}

	/**
	 * 显示水表审核页面数据
	 * @return
	 */
	public String planList(){
		QueryFilter filter=new QueryFilter(getRequest());
		String month,planName,executor;
		month = getRequest().getParameter("Q_month_S_EQ");
		planName = getRequest().getParameter("Q_planName_S_LK");
		executor =getRequest().getParameter("Q_executor_S_LK");
		String depId = departmentService.getSubDepIds();
		List<WaterMeterPlan> planList = pdaWaterListService.getWaterPlan(month, planName, executor,depId,filter);
		for(int i=0;i<planList.size();i++){
			if(planList.get(i).getPlanStatus()==3||planList.get(i).getPlanStatus()==4){
				List<PdaWaterList> statusList = pdaWaterListService.checkStatus(planList.get(i).getPlanId(),planList.get(i).getLastEditBy());
			   if(statusList!=null && statusList.size()>0){
				   planList.get(i).setPlanStatus(2l);
			   }
			}
		}
		JSONSerializer serializer=new JSONSerializer();
		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
		.append(pdaWaterListService.getWaterPlanNumb(month, planName, executor, depId)).append(",result:");		
        buff.append(serializer.exclude(new String[] { "class" }).serialize(planList));
		buff.append("}");
				
		jsonString=buff.toString();	
		System.out.print(jsonString);
		return SUCCESS;
	}
	
	/**
	 * 按照計劃審核
	 * @return
	 */
	public String checkPlan(){
		String ids = fileName.trim();
		String month = getRequest().getParameter("Q_month_S_EQ");
		if(ids.endsWith(",")){
			ids = ids.substring(0, ids.length()-1);
		}
		if(ids.contains("'")){
			setJsonString("{success:false}");
		}else{
			String status = "1"; //通过
			boolean ynOk=pdaWaterListService.checkPlan(ids,status,month);
			setJsonString("{success:"+ynOk+"}");
		}		
		return SUCCESS;
	}
	
	/**
	 * 审核明细查询
	 */
	public String checkDetailSearch(){
		QueryFilter filter=new QueryFilter(getRequest());		
		String planId = getRequest().getParameter("Q_planId_S_EQ");
		String planName = getRequest().getParameter("Q_planName_S_EQ");
		String month = getRequest().getParameter("Q_month_S_EQ");
		String executor ="";// getRequest().getParameter("Q_executor_S_EQ");
		String fangId = getRequest().getParameter("aparmentId_S_LK");
		String waterId = getRequest().getParameter("Q_amId_S_LK");
		String dongId = getRequest().getParameter("buildingId_S_LK");
		String quId = getRequest().getParameter("districtId_S_LK");
		String depId = departmentService.getSubDepIds();
		List<PdaWaterList>  list=pdaWaterListService.getCheckDetailSearch(planId, planName, month, executor, fangId, waterId, dongId, quId,depId,filter);
		List<PdaWaterList> list1= new ArrayList<PdaWaterList>();
		for(int i=0;i<list.size();i++){
			if(list.get(i).getStatus().equals("0")){
				list.get(i).setRemark("待审核");	
			}else if(list.get(i).getStatus().equals("2")){
				list.get(i).setRemark("这个月读数小于上个月读数");	
			}else if(list.get(i).getStatus().equals("3")){
				list.get(i).setRemark("本月读数大于上月与去年同月读数平均數的10%");	
			}else if(list.get(i).getStatus().equals("4")){
				list.get(i).setRemark("换表");	
			}else {
				list.get(i).setRemark("");	
			}
			list.get(i).setCreateddt(planName);
			list.get(i).setLastDegree(pdaWaterListService.getPdaWaterList(list.get(i)));
		}
		
		JSONSerializer serializer=new JSONSerializer();
		StringBuffer buff = new StringBuffer("{success:true,'totalCounts':")
		.append(pdaWaterListService.getCheckDetailSearchNumb(planId, planName, month, executor, fangId, waterId, dongId, quId, depId)).append(",result:");		
        buff.append(serializer.exclude(new String[] { "class" }).serialize(list));
		buff.append("}");
				
		jsonString=buff.toString();		
		return SUCCESS;
	}
	
	
	/**
	 * 获取当前用户下属的未删除所有水表的id
	 * @return 如"101,12,15"
	 */
	private String getSubMeterIds() {
		String ids = departmentService.getSubDepIds();
		if(!ids.isEmpty()){
			QueryFilter filter = new QueryFilter(0,Integer.MAX_VALUE);
			filter.addFilter("Q_department.depId_S_LIN", ids);//只查当前用户权限下的管理处
			List<PdaWaterMeter> mlist = pdaWaterMeterService.getAll(filter);
			ids = "";
			if(mlist.size()>0){
				for (PdaWaterMeter pdaWaterMeter : mlist) {
					ids += pdaWaterMeter.getAmId()+",";		
				}
				ids = ids.substring(0, ids.length()-1);
			}	
		}
		return ids;
	}
}
